// Package bootstrap provides enhanced server startup with Gin integration
package bootstrap

import (
	"context"
	"flag"
	"fmt"
	"net/http"
	"os"
	"os/signal"  
	"runtime"
	"syscall"
	"time"

	"gitee.com/zhenyangze/gin-framework/internal/handlers"
	"gitee.com/zhenyangze/gin-framework/routes"
	"github.com/gin-gonic/gin"
)

var (
	h bool
	t string
	p string
	d bool
	c string
)

func init() {
	flag.BoolVar(&h, "h", false, "help")
	flag.StringVar(&t, "t", "web", "Run Type[web,cron,rpc,all]")
	flag.StringVar(&p, "p", ":8080", "Port")
	flag.BoolVar(&d, "d", false, "Debug")
	flag.StringVar(&c, "c", "configs", "Config Path")
}

// Start starts the server with the new architecture
func (b *Bootstrapper) Start() error {
	flag.Parse()

	if h {
		usage()
		return nil
	}

	// Set GOMAXPROCS
	runtime.GOMAXPROCS(runtime.NumCPU())
	
	// Set Gin mode
	if d {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}

	// Create Gin router
	router := gin.New()
	router.Use(gin.Recovery())

	// Add health check endpoints
	healthHandler := handlers.NewHealthHandler(b.container)
	router.GET("/health", healthHandler.HealthCheck)
	router.GET("/health/ready", healthHandler.ReadinessCheck)
	router.GET("/health/live", healthHandler.LivenessCheck)
	router.GET("/metrics", healthHandler.MetricsHandler)

	// Setup routes based on type
	switch t {
	case "web":
		b.container.Event().Publish("main:init")
		routes.Web(router)
		routes.Websocket(router)
	case "cron":
		routes.Cron(router)
	case "rpc":
		routes.Rpc(router)
	case "all":
		b.container.Event().Publish("main:init")
		routes.Web(router)
		routes.Websocket(router)
		routes.Cron(router)
		routes.Rpc(router)
	}

	// Create HTTP server
	srv := &http.Server{
		Addr:    p,
		Handler: router,
	}

	// Start server in goroutine
	go func() {
		b.logger.Info("Starting server", "port", p, "mode", gin.Mode())
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			b.logger.Error("listen", "error", err)
		}
	}()

	// Wait for interrupt signal
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	b.logger.Info("Shutdown Server ...")

	// Graceful shutdown
	waitTimes := b.config.GetInt64Default("app.wait_time", 5)
	ctx, cancel := context.WithTimeout(context.Background(), time.Duration(waitTimes)*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		b.logger.Error("Server Shutdown", "error", err)
		return err
	}

	// Shutdown application services
	if err := b.container.Stop(); err != nil {
		b.logger.Error("Container shutdown error", "error", err)
		return err
	}

	b.logger.Info("Server exited")
	return nil
}

func usage() {
	fmt.Fprintf(os.Stderr, `gin-framework: v2.0.0
Usage: main [-h] [-t type] [-d debug] [-p port]

Options:
`)
	flag.PrintDefaults()
}